# -*- encoding: utf-8 -*-
#简化geojson，缩短小数点后位数并清空properties
import json
import os
import codecs
from decimal import Decimal
def Persist(num):
    num=Decimal(num)
    num=round(num,6)
    return num
def SimplifyGeometry(geometry):
    """
    convert wgs84 to gcj
    referencing by https://github.com/wandergis/coordTransform_py
    """
    # TODO: point linestring point
    if geometry['type'] == 'MultiLineString':
        coordinates = geometry['coordinates']
        for lines in coordinates:
            for line in lines:
                line[0] = Persist(line[0])
                line[1] = Persist(line[1])
    if geometry['type'] == 'LineString':
        coordinates = geometry['coordinates']
        for lines in coordinates:
            line[0] = Persist(line[0])
            line[1] = Persist(line[1])
    if geometry['type'] == 'Polygon':
        coordinates = geometry['coordinates']
        for parts in coordinates:
            for points in parts:
                points[0]= Persist(points[0])
                points[1] = Persist(points[1])
    if geometry['type'] == 'MultiPolygon':
        coordinates = geometry['coordinates']
        for multi_parts in coordinates:
            for parts in multi_parts:
                for points in parts:
                    points[0]= Persist(points[0])
                    points[1] = Persist(points[1])
    if geometry['type'] == 'Point':
        coordinates = geometry['coordinates']
        coordinates[0]= Persist(coordinates[0])
        coordinates[1] = Persist(coordinates[1])
    return geometry

def doSimplify():
    path=os.path.dirname(os.path.realpath(__file__))#获取py文件所在文件夹
    txtDirPath=path+'\\geojson\\'
    simplifyPath=path+'\\simplify\\'
    pathDir =  os.listdir(txtDirPath)
    for allDir in pathDir:
        child = os.path.join('%s%s' % (txtDirPath, allDir))
        childPath=child.decode('gbk') # .decode('gbk')是解决中文显示乱码问题
        with open(childPath, 'r') as file:
            json_data = file.read()
            json_data = json.loads(json_data)
            features = json_data['features']
            for feature in features:
                feature['geometry'] = SimplifyGeometry(feature['geometry'])
                feature['properties']="{}"
            outPutPath=os.path.splitext(childPath)[0]+'Simplify.geojson'
            with codecs.open(outPutPath, 'w+', "utf-8") as wfile:
                geojson=json.dumps(json_data)
                geojson.replace('u\'','\'')
                geojson=geojson.decode("unicode-escape") 
                wfile.write(geojson)
                print('success')
if __name__ == '__main__':
    doSimplify()